package com.example.shixun1.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.shixun1.R;
import com.example.shixun1.adapter.AccountAdapter;
import com.example.shixun1.model.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class AccountManageActivity extends AppCompatActivity
        implements AccountAdapter.AccountActionListener {

    private static final int REQUEST_CHANGE_PASSWORD = 1001;
    private AccountAdapter adapter;
    private final List<User> accountList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_manage);

        loadAccounts();
        setupRecyclerView();
        setupAddButton();
    }

    private void loadAccounts() {
        SharedPreferences prefs = getSharedPreferences("users", MODE_PRIVATE);
        Map<String, ?> allEntries = prefs.getAll();

        for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
            if (entry.getKey().endsWith("_username")) {
                String username = (String) entry.getValue();
                String password = prefs.getString(username + "_password", "");
                boolean isAdmin = prefs.getBoolean(username + "_admin", false);
                accountList.add(new User(username, password, isAdmin));
            }
        }
    }

    private void setupRecyclerView() {
        RecyclerView recyclerView = findViewById(R.id.rv_accounts);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AccountAdapter(this, accountList, this);
        recyclerView.setAdapter(adapter);
    }

    private void setupAddButton() {
        findViewById(R.id.btn_add_account).setOnClickListener(v -> {
            startActivity(new Intent(this, RegisterActivity.class));
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_account_manage, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_toggle_passwords) {
            adapter.toggleAllPasswordsVisibility();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onEditAccount(int position, User user) {
        Intent intent = new Intent(this, ChangePasswordActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("username", user.getUsername());
        startActivityForResult(intent, REQUEST_CHANGE_PASSWORD);
    }

    @Override
    public void onDeleteAccount(int position, User user) {
        // 检查是否是当前登录用户
        SharedPreferences loginPrefs = getSharedPreferences("login_state", MODE_PRIVATE);
        String currentUser = loginPrefs.getString("current_user", "");

        if (user.getUsername().equals(currentUser)) {
            Toast.makeText(this, "不能删除当前登录的账号", Toast.LENGTH_SHORT).show();
            return;
        }

        // 1. 从用户数据中完全删除
        SharedPreferences.Editor editor = getSharedPreferences("users", MODE_PRIVATE).edit();

        // 删除所有与该用户相关的键
        editor.remove(user.getUsername() + "_username");
        editor.remove(user.getUsername() + "_password");
        editor.remove(user.getUsername() + "_phone");
        editor.remove(user.getUsername() + "_admin");

        // 确保提交更改
        editor.apply();

        // 2. 从内存列表中删除
        accountList.remove(position);

        // 3. 通知适配器更新
        adapter.notifyItemRemoved(position);

        // 4. 立即强制同步SharedPreferences
        getSharedPreferences("users", MODE_PRIVATE)
                .edit()
                .commit(); // 使用commit()确保立即写入

        Toast.makeText(this, "账号已彻底删除", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onToggleAdminStatus(int position, User user) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CHANGE_PASSWORD && resultCode == RESULT_OK) {
            int position = data.getIntExtra("position", -1);
            String newPassword = data.getStringExtra("new_password");
            if (position != -1) {
                adapter.updatePassword(position, newPassword);
                updatePasswordInPrefs(accountList.get(position).getUsername(), newPassword);
                Toast.makeText(this, "密码更新成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void updatePasswordInPrefs(String username, String newPassword) {
        getSharedPreferences("users", MODE_PRIVATE).edit()
                .putString(username + "_password", newPassword)
                .apply();
    }

    // ...实现其他接口方法...
}